package com.qf.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.qf.constant.MessageConstant;
import com.qf.constant.RedisConstant;
import com.qf.entity.PageResult;
import com.qf.entity.QueryPageBean;
import com.qf.entity.Result;
import com.qf.pojo.Setmeal;
import com.qf.service.SetMealService;
import com.qf.utils.QiniuUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import redis.clients.jedis.JedisPool;

import java.io.IOException;
import java.util.UUID;

/**
 * @author zhouhao
 * @create 2021-12-22 20:05
 */
@RestController
@RequestMapping("setmeal")
public class SetMealController {

    @Reference
    private SetMealService setMealService;

    @Autowired
    private JedisPool jedisPool;

    //文件上传
    @RequestMapping("upload.do")
    public Result upload(@RequestParam("imgFile") MultipartFile imFile){
        System.out.println(imFile);
        //获取原始的文件上传的名字,主要用来截取文件后缀
        String originalFilename = imFile.getOriginalFilename();
        int index = originalFilename.lastIndexOf(".");
        String extention = originalFilename.substring(index); //.jpg
        String fileName =  UUID.randomUUID().toString()+extention;//文件上传后的名称
        try {
            //将图片名称存入Redis中,基于redis的set集合存储
            jedisPool.getResource().sadd(RedisConstant.SETMEAL_PIC_RESOURCES,fileName);
            QiniuUtils.upload2Qiniu(imFile.getBytes(),fileName);
            return new Result(true,MessageConstant.PIC_UPLOAD_SUCCESS,fileName);
        } catch (IOException e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.PIC_UPLOAD_FAIL);
        }
    }

    //添加套餐
    @RequestMapping("add.do")
    public Result add(@RequestBody Setmeal setmeal ,Integer[] checkgroupIds){
        System.out.println(setmeal);
        System.out.println(checkgroupIds);
        try {
            setMealService.add(setmeal,checkgroupIds);
            return new Result(true,MessageConstant.ADD_SETMEAL_SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,MessageConstant.ADD_SETMEAL_FAIL);
        }
    }

    //分页查询套餐
    @RequestMapping("findPage")
    public PageResult findPage(@RequestBody QueryPageBean queryPageBean){
        PageResult pageResult =  setMealService.findPage(queryPageBean);
        return pageResult;
    }

}
